package com.zhuizikejithreeig.cn.threeigkeji.loginfo;

import android.Manifest;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;

import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.bigkoo.pickerview.TimePickerView;
import com.zhuizikejithreeig.cn.been.ImageBeen;

import com.zhuizikejithreeig.cn.content.UriContect;
import com.zhuizikejithreeig.cn.threeigkeji.BasicActivity;
import com.zhuizikejithreeig.cn.threeigkeji.CompontApplayCation;
import com.zhuizikejithreeig.cn.threeigkeji.R;
import com.zhuizikejithreeig.cn.utils.AppManager;
import com.zhuizikejithreeig.cn.utils.BitmapFileSetting;
import com.zhuizikejithreeig.cn.utils.FileUtil;
import com.zhuizikejithreeig.cn.utils.GsonUtil;
import com.zhuizikejithreeig.cn.utils.ImageUtil;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import de.hdodenhof.circleimageview.CircleImageView;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;

public class BasicInfoActivity extends BasicActivity implements View.OnClickListener {
    private static final int    PHOTOANDSD_PERMISS = 101;
    private static final int    SDK_PERMISS        = 111;
    private static final int    IMAGE_ONE_ONE      = 121;
    private              String IMAGE_TYPE         = "image/*";
    private static final int    REQ_2              = 4;
    private TextView        mName1;
    private CircleImageView mProfileImage;
    private TextView        mText1;
    private EditText        mName4;
    private EditText        mName2;
    private TextView        mName7;
    private RelativeLayout  mName8;
    private String          mFilePath;
    private Bitmap          mStream;
    private Uri             mOriginalUri;
    private ImageView           mImage;
    private int idcard = 0;
    private TimePickerView pvTime;
    private String mFilePathIcon;
    private String mFilePathId;
    private long exitTime=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showBody();
        setContentView_V(R.layout.activity_basic_info);
        pvTime = getTimePickerView();
        //先指定路径
        mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        mFilePathIcon = mFilePath + "/" +1+ ".jpg";
        mFilePathId = mFilePath + "/" + 2 + ".jpg";
        mName1 = (TextView) findViewById(R.id.name1);
        mText1 = (TextView) findViewById(R.id.text1);
        mName7 = (TextView) findViewById(R.id.name7);
        mImage = (ImageView) findViewById(R.id.image);

        mProfileImage = (CircleImageView) findViewById(R.id.profile_image);
        mName8 = (RelativeLayout) findViewById(R.id.name8);


        mName4 = (EditText) findViewById(R.id.name4);
        mName2 = (EditText) findViewById(R.id.name2);

        mProfileImage.setOnClickListener(this);
        mName1.setOnClickListener(this);
        mName8.setOnClickListener(this);
        mName7.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (CompontApplayCation.carinfook){
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            //更换头像
            case R.id.profile_image:

                idcard = 1;
                //TODO:获取相机和读取内存卡权限

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ToastMake.showToast(getResources().getString(R.string.string82));
                    hasCarePermission(Manifest.permission.CAMERA);
                    return;
                }

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ToastMake.showToast(getResources().getString(R.string.string83));
                    hasIdCardPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    return;
                }
                showChoiceDialog();
                break;
            //下一步
            case R.id.name1:
                String name = mName4.getText().toString().trim();
                String id = mName2.getText().toString().trim();
                String time = mName7.getText().toString().trim();
                if (mStream == null) {
                    ToastMake.showToast(getResources().getString(R.string.string77));
                    return;
                }
                if (mName4 == null || TextUtils.equals(name, "")) {
                    ToastMake.showToast(getResources().getString(R.string.string78));
                    return;
                }
                if (mName2 == null || TextUtils.equals(id, "")) {
                    ToastMake.showToast(getResources().getString(R.string.string79));
                    return;
                }
                //   验证身份证
                if (!Utils.isIdNumber(id)) {
                    return;
                }
                if ( CompontApplayCation.driverInfo.getIcon()==null){
                    ToastMake.showToast(getResources().getString(R.string.string77));
                    return;
                }
                //TODO:并且选择时间不能大于当前的时间time.contains("xx")
                if (TextUtils.equals(time,getResources().getString(R.string.string93))) {
                    ToastMake.showToast(getResources().getString(R.string.string81));
                    return;
                }


                if ( CompontApplayCation.driverInfo.getId()==null){
                    ToastMake.showToast(getResources().getString(R.string.string80));
                    return;
                }


                Intent intent = new Intent();
                intent.setClass(BasicInfoActivity.this, CarInformationActivity.class);
                CompontApplayCation.driverInfo.setCard(id);
                CompontApplayCation.driverInfo.setName(name);
                CompontApplayCation.driverInfo.setReceive(time);
                startActivity(intent);
                break;
            //身份证
            case R.id.name8:
                idcard = 2;
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ToastMake.showToast(getResources().getString(R.string.string82));
                    hasCarePermission(Manifest.permission.CAMERA);
                    return;
                }

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ToastMake.showToast(getResources().getString(R.string.string83));
                    hasIdCardPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    return;
                }
                showChoiceDialog();
                break;
            //选择时间
            case R.id.name7:

                InputMethodManager imm = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mName7.getWindowToken(), 0);
                pvTime.show();
                break;
        }

    }

    @NonNull
    private TimePickerView getTimePickerView() {
        TimePickerView pvTime = new TimePickerView.Builder(BasicInfoActivity.this, new TimePickerView.OnTimeSelectListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onTimeSelect(Date date2, View v) {//选中事件回调

                long chioceDate = Utils.dateToLong(date2);
                long curDate = Utils.getCurDate();
                if (chioceDate >= curDate) {
                    ToastMake.showToast("时间必须小于当前时间");
                    return;
                } else {
                    String time = getTime(date2);
                    mName7.setText(time);
                    mName7.setTextColor(getResources().getColor(R.color.textColor5));
                }
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(20)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("请选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                //                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
                //                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
                //                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
                //                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                //                        .setRangDate(startDate,endDate)//起始终止年月日设定
                //                        .setLabel("年","月","日","时","分","秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                //                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        return pvTime;
    }


    private void hasIdCardPermission(String permission) {
        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{permission},
                        SDK_PERMISS);

            } else {
                //TODO:权限申请成功
            }

        }


    }

    private void hasCarePermission(String permission) {
        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{permission},
                        PHOTOANDSD_PERMISS);
            } else {
                //TODO:权限申请成功
            }

        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PHOTOANDSD_PERMISS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //TODO:相机权限申请成功
            } else {
                //判断是否勾选禁止后不再询问
                boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(BasicInfoActivity.this, Manifest.permission.CAMERA);
                if (showRequestPermission) {
                    //TODO:相机权限申请成功

                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    //        Uri uri = Uri.fromParts("package", context.getPackageName());
                    //        intent.setData(uri);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                }

            }
        } else if (requestCode == SDK_PERMISS) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //TODO:SDK权限申请成功
            } else {
                //判断是否勾选禁止后不再询问
                boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(BasicInfoActivity.this, permissions[0]);
                if (showRequestPermission) {
                    //TODO:SDK权限申请成功

                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    //        Uri uri = Uri.fromParts("package", context.getPackageName());
                    //        intent.setData(uri);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                }

            }

        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void showChoiceDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(BasicInfoActivity.this);
        builder.setTitle("选择照片来源");
        final String[] single_list = {"相册", "相机"};
        builder.setSingleChoiceItems(single_list, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String str = single_list[which];
                if (str.equals("相册")) {
                    //这里读取相册
                    onStartPhotoPicture();

                } else {
                    //这里读取相机
                    startBigCameral();
                }
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }



    private void onStartPhotoPicture() {
        // TODO Auto-generated method stub
        boolean isKitKatO = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        Intent getAlbum;
        if (isKitKatO) {
            getAlbum = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        } else {
            getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
        }
        getAlbum.setType(IMAGE_TYPE);
        startActivityForResult(getAlbum, IMAGE_ONE_ONE);
    }

    //调取大图
    public void startBigCameral() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQ_2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            //获取相机照片
            if (requestCode == REQ_2) {
                mStream = null;
                mStream = data.getParcelableExtra("data");
                mText1.setVisibility(View.GONE);

                //设置头像信息并保存起来
                if (idcard==1) {
                    File file = BitmapFileSetting.saveBitmapFile(mStream, mFilePathIcon);
                    mProfileImage.setImageBitmap(mStream);
                    CompontApplayCation.driverInfo.setIcon(file);

                }else if (idcard==2){
                    File file = BitmapFileSetting.saveBitmapFile(mStream, mFilePathId);
                    mImage.setImageBitmap(mStream);
                    mImage.setScaleType(ImageView.ScaleType.FIT_XY);
                    CompontApplayCation.driverInfo.setId(file);
                }

                //获取相册照片
            } else if (requestCode == IMAGE_ONE_ONE) {
                ContentResolver resolver = getContentResolver();
                //获得图片的uri
                mOriginalUri = data.getData();
                mText1.setVisibility(View.GONE);
                //这里已经对获得照片进行了压缩处理
                try {
                    mStream = null;
                    //TODO:解决bitmap不能正常展示的图片
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(resolver, mOriginalUri);
                    if (bitmap.getByteCount()<=1024){
                        mStream = bitmap;
                    }else {
                        mStream = ImageUtil.getImage(bitmap);
                    }
                    //设置头像信息并保存起来
                    if (idcard==1) {
                        File file = BitmapFileSetting.saveBitmapFile(mStream, mFilePathIcon);
                        mProfileImage.setImageBitmap(mStream);
                        CompontApplayCation.driverInfo.setIcon(file);
                    }else if (idcard==2){
                        File file = BitmapFileSetting.saveBitmapFile(mStream, mFilePathId);
                        mImage.setImageBitmap(mStream);
                        mImage.setScaleType(ImageView.ScaleType.FIT_XY);
                        CompontApplayCation.driverInfo.setId(file);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    mText1.setVisibility(View.VISIBLE);
                }

            }
            System.out.println(mStream);
        }
    }
    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        return format.format(date);
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastMake.showToast(getResources().getString(R.string.string28));
                exitTime = System.currentTimeMillis();
                return true;
            } else {
                Activity activity = AppManager.getInstance().getActivity(LoginActivity.class);
                if (activity!=null){
                    AppManager.getInstance().finishActivity(LoginActivity.class);
                }
                AppManager.getInstance().finishActivity(this);
                finish();
            }
            return true;
        }
        return true;
    }
}


